// pages/index/index.js
var utils = require("../../utils/util.js");
var reachBottomTimeout = null;
var cid = "hexunminiprogram";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    "logo_url": "https://i8.hexun.com/2016/m/20171016/img/logonew.png",
    channel: [],
    channelCount: 0,
    items: [],
    num: 0,
    isMore: 0,
    isGotopShow: false,
    isRefreshShow: true,
    type: "index",
    currentNav: 0,
    isLoading: false,
    isRefreshError: false,
    cid: cid //(Math.random()+"").replace(/\./gim, "")
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    /*var then = this;
    wx.onNetworkStatusChange(function(res){
      console.log(res)
      if (res.networkType === 'none'){
        then.setData({
          isMore: 3
        })
      }else{
        wx.startPullDownRefresh({
          success: function(){
            then.initDataList();
          }
        })
      }
    });*/
    var then = this;
    options && options.type && this.setData({
      type: options.type,
      currentNav: options.i && parseInt(options.i) || 0,
      newsId: options.id
    })
    wx.getStorage({
      key: this.data.type,
      success: function (res) {
        console.log(res)
        then.setData({
          items: res.data
        })
      },
      fail: function () {

      }
    })
    this.data.newsId && wx.navigateTo({
      url: '../../pages/view/view?id=' + this.data.newsId + "&chid=" + this.data.type + "&navid=" + this.data.currentNav,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var channel = utils.getChannel(cid);
    this.setData({
      channel: channel,
      channelCount: channel.length/2
    })
    this.initDataList();

    /*var then = this;
    wx.onAccelerometerChange(function (e) {
      console.log(e.x)
      console.log(e.y)
      console.log(e.z)
      if (e.x > 1 && e.y > 1) {
        wx.showToast({
          title: '摇一摇成功，刷新列表',
          icon: 'success',
          duration: 2000,
          success: function () {
            then.initDataList();
          }
        })
      }
    })*/
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  onPageScroll: function (options) {
    // console.log(options)
    if (options.scrollTop > 100) {
      this.setData({
        isGotopShow: true
      })
    } else {
      this.setData({
        isGotopShow: false
      })
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.initDataList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var then = this;
    reachBottomTimeout && clearTimeout(reachBottomTimeout);
    reachBottomTimeout = setTimeout(function () {
      then.addNewDataList();
    }, 50)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      title: "和讯网 - " + this.data.channel[this.data.currentNav].title,
      path: "/pages/index/index?type=" + this.data.type + "&i=" + this.data.currentNav,
      success: function (res) {
        wx.showToast({
          title: '转发成功',
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '转发失败',
        })
      }
    }
  },
  initDataList: function () {
    if (!this.data.isLoading) {
      this.data.isLoading = true;
      wx.showNavigationBarLoading()
      var then = this;
      then.data.num = 0;
      wx.request({
        url: then.router(then.data.type, then.defaultRouteArge(then.data.type)),
        data: {},
        success: function (res) {
          //console.log(res.data)
          var result = res.data,
            data = [];
          if (result.status && result.status === 1 && result.data.length > 0 || result.length > 0) {
            (result.data || result).forEach(function (item) {
              if (item.itemid && !/b_/.test(item.itemid) || !item.itemid) {
                if (item.newsSubtype && !/4|5/.test(item.newsSubtype) || !item.itemid) data.push(then.mixData(then.data.type, {}, item))
              }
            })
            then.setData({
              items: data,
              isMore: 1,
              isRefreshError: false
            })
            wx.setStorage({
              key: then.data.type,
              data: data,
            })
            wx.vibrateShort()
          }
          wx.hideNavigationBarLoading()
          then.data.isLoading = false;
        },
        fail: function () {
          then.setData({
            isRefreshError: true
          })
          wx.hideNavigationBarLoading()
          then.data.isLoading = false;
        }
      })
    }
  },
  addNewDataList: function () {
    if (!this.data.isLoading) {
      if (this.data.num + 1 < 5) {
        this.data.isLoading = true;
        this.data.num += 1;
        wx.showNavigationBarLoading()
        var then = this;
        wx.request({
          url: then.router(then.data.type, then.moreRouteArge(then.data.type)),
          data: {},
          success: function (res) {
            //console.log(res.data)
            var result = res.data,
              data = then.data.items;
            if (result.status && result.status === 1 && result.data.length > 0 || result.length > 0) {
              (result.data || result).forEach(function (item) {
                if (item.itemid && !/b_/.test(item.itemid) || !item.itemid) {
                  if (item.newsSubtype && !/4|5/.test(item.newsSubtype) || !item.itemid) data.push(then.mixData(then.data.type, {}, item))
                }
              })
              then.setData({
                items: data,
                isMore: then.data.num + 1 >= 5 ? 2 : 1
              })
            }
            wx.hideNavigationBarLoading()
            then.data.isLoading = false;
          },
          fail: function () {
            then.data.num -= 1;
            then.setData({
              isMore: 3
            })
            wx.hideNavigationBarLoading()
            then.data.isLoading = false;
          }
        })
      } else {
        this.setData({
          isMore: 2
        })
      }
    }
  },
  mixData: function (type, obj, item) {
    switch (type) {
      case "index":
        return {
          title: item.title,
          img: item.newsPicture.toLocalPic().replace(/http\:/gim, "https:"),
          path: "../../pages/view/view?id=" + item.itemid + "&chid=" + this.data.type + "&navid=" + this.data.currentNav,
          media: item.mediaName,
          time: (item.item_modify_time + "").toLocalTime("yyyy-MM-dd")
        };
        break;
      default:
        return {
          title: item.NewsTitle,
          img: item.NewsPic.toLocalPic().replace(/http\:/gim, "https:"),
          path: "../../pages/view/view?id=" + item.NewsID + "&chid=" + this.data.type + "&navid=" + this.data.currentNav,
          media: item.Media,
          time: item.NewsTime
        };
        break;
    }
  },
  router: function (type, args) {
    var then = this;
    switch (type) {
      case "index":
        return utils.api.list.tmpl(args);
        break;
      default:
        return utils.api.newsList.tmpl(args);
        break;
    }
  },
  moreRouteArge: function (type) {
    var then = this;
    var cid = then.data.cid;
    for (var i = 0; i < then.data.channel.length; i++) {
      var item = then.data.channel[i];
      if (item.type === type) {
        return utils.extend(utils.extend({}, item.apiArgs), type === "index" ? {
          num: then.data.num * 20
        } : {
            count: then.data.num + 1
          });
        break;
      }
    }
    /*switch (type) {
      case "index":
        return {
          num: then.data.num * 20,
          cateid: "",
          cid: cid
        };
        break;
      case "tech":
        return {
          id: 19,
          count: then.data.num + 1
        };
        break;
      case "bank":
        return {
          id: 10,
          count: then.data.num + 1
        };
        break;
      case "money":
        return {
          id: 13,
          count: then.data.num + 1
        };
        break;
      case "house":
        return {
          id: 17,
          count: then.data.num + 1
        };
        break;
      case "auto":
        return {
          id: 18,
          count: then.data.num + 1
        };
        break;
      case "insurance":
        return {
          id: 11,
          count: then.data.num + 1
        };
        break;
      case "quote_futures":
        return {
          id: 6,
          count: then.data.num + 1
        };
        break;
      case "news":
        return {
          id: 1,
          count: then.data.num + 1
        };
        break;
      case "stock":
        return {
          id: 2,
          count: then.data.num + 1
        };
        break;
    }*/
  },
  defaultRouteArge: function (type) {
    var then = this;
    var cid = then.data.cid;
    for (var i = 0; i < then.data.channel.length; i++) {
      var item = then.data.channel[i];
      if (item.type === type) {
        return utils.extend({}, item.apiArgs);
        break;
      }
    }
    /*switch (type) {
      case "index":
        return {
          num: then.data.num,
          cateid: "",
          cid: cid
        };
        break;
      case "tech":
        return {
          id: 19,
          count: 0
        };
        break;
      case "bank":
        return {
          id: 10,
          count: 0
        };
        break;
      case "money":
        return {
          id: 13,
          count: 0
        };
        break;
      case "house":
        return {
          id: 17,
          count: 0
        };
        break;
      case "auto":
        return {
          id: 18,
          count: 0
        };
        break;
      case "insurance":
        return {
          id: 11,
          count: 0
        };
        break;
      case "quote_futures":
        return {
          id: 6,
          count: 0
        };
        break;
      case "news":
        return {
          id: 1,
          count: 0
        };
        break;
      case "stock":
        return {
          id: 2,
          count: 0
        };
        break;
    }*/
  },
  gotop: function () {
    wx.pageScrollTo({ scrollTop: 0 })
  },
  refresh: function () {
    if (!this.data.isLoading) {
      wx.startPullDownRefresh()
    }
  }
})